<template>
  <div class="chat-container">
    <!-- 聊天记录区域 -->
    <div class="chat-messages" ref="messagesRef">
      <div v-for="(message, index) in chatMessages" :key="index" :class="['message', message.role]">
        <div class="avatar">
          <el-avatar :size="40" :src="message.role === 'user' ? userAvatar : aiAvatar" />
        </div>
        <div class="content">
          <div class="name">{{ message.role === "user" ? "我" : "AI助手" }}</div>
          <div class="text" v-html="formatMessage(message.content)"></div>
          <div class="time">{{ formatTime(message.time) }}</div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="chat-input">
      <el-input
        v-model="inputMessage"
        type="textarea"
        :rows="3"
        placeholder="请输入您的问题..."
        @keyup.enter.ctrl="sendMessage"
      />
      <div class="input-actions">
        <el-button @click="clearChat" :disabled="isLoading">清空对话</el-button>
        <el-button type="primary" @click="sendMessage" :loading="isLoading">
          {{ isLoading ? "思考中..." : "发送" }}
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from "vue";
import { ElMessage } from "element-plus";
import { marked } from "marked";
import hljs from "highlight.js";
import "highlight.js/styles/github.css";

// 类型定义
interface ChatMessage {
  role: "user" | "assistant";
  content: string;
  time: number;
}

// 状态变量
const inputMessage = ref("");
const isLoading = ref(false);
const messagesRef = ref<HTMLElement>();
const chatMessages = ref<ChatMessage[]>([
  {
    role: "assistant",
    content: "你好！我是AI助手，很高兴为您服务。请问有什么我可以帮您的吗？",
    time: Date.now(),
  },
]);

// 头像配置
const userAvatar = "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png";
const aiAvatar = "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png";

// 配置 marked
marked.setOptions({
  highlight: function (code, lang) {
    const language = hljs.getLanguage(lang) ? lang : "plaintext";
    return hljs.highlight(code, { language }).value;
  },
  langPrefix: "hljs language-",
});

// 格式化消息内容（支持 Markdown）
const formatMessage = (content: string) => {
  return marked(content);
};

// 格式化时间
const formatTime = (timestamp: number) => {
  return new Date(timestamp).toLocaleTimeString();
};

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim() || isLoading.value) return;

  // 添加用户消息
  chatMessages.value.push({
    role: "user",
    content: inputMessage.value,
    time: Date.now(),
  });

  const userQuestion = inputMessage.value;
  inputMessage.value = "";
  isLoading.value = true;

  try {
    // 模拟AI响应
    await new Promise((resolve) => setTimeout(resolve, 1000));

    // TODO: 替换为实际的通义千问API调用
    const aiResponse = await mockAIResponse(userQuestion);

    chatMessages.value.push({
      role: "assistant",
      content: aiResponse,
      time: Date.now(),
    });

    // 滚动到底部
    await nextTick();
    if (messagesRef.value) {
      messagesRef.value.scrollTop = messagesRef.value.scrollHeight;
    }
  } catch (error) {
    ElMessage.error("抱歉，请求失败，请稍后重试");
  } finally {
    isLoading.value = false;
  }
};

// 清空对话
const clearChat = () => {
  chatMessages.value = [
    {
      role: "assistant",
      content: "对话已清空。有什么我可以帮您的吗？",
      time: Date.now(),
    },
  ];
};

// 模拟AI响应
const mockAIResponse = async (question: string) => {
  // 这里可以替换为实际的通义千问API调用
  const responses: { [key: string]: string } = {
    你好: "你好！很高兴见到你。",
    介绍一下自己: "我是基于通义千问的AI助手，可以帮助回答问题、编写代码、解释概念等。",
    默认:
      '我理解您的问题是关于"' +
      question +
      '"。让我思考一下...\n\n' +
      "这是一个很好的问题。根据我的理解...",
  };

  return responses[question] || responses["默认"];
};

// 监听滚动
onMounted(() => {
  if (messagesRef.value) {
    messagesRef.value.scrollTop = messagesRef.value.scrollHeight;
  }
});
</script>

<style scoped>
.chat-container {
  height: calc(100vh - 84px);
  display: flex;
  flex-direction: column;
  background-color: var(--el-bg-color-page);
  padding: 20px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: var(--el-bg-color);
  border-radius: 8px;
  box-shadow: var(--el-box-shadow-light);
  margin-bottom: 20px;
}

.message {
  display: flex;
  margin-bottom: 20px;
  animation: fadeIn 0.3s ease;
}

.message.user {
  flex-direction: row-reverse;
}

.avatar {
  margin: 0 12px;
}

.content {
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 8px;
  background: var(--el-color-primary-light-9);
  position: relative;
}

.message.user .content {
  background: var(--el-color-primary);
  color: white;
}

.message.user .content .time,
.message.user .content .name {
  color: rgba(255, 255, 255, 0.8);
}

.name {
  font-size: 14px;
  margin-bottom: 4px;
  color: var(--el-text-color-secondary);
}

.text {
  line-height: 1.6;
  font-size: 15px;
  white-space: pre-wrap;
}

.time {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 4px;
}

.chat-input {
  background: var(--el-bg-color);
  padding: 20px;
  border-radius: 8px;
  box-shadow: var(--el-box-shadow-light);
}

.input-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 12px;
}

:deep(.el-textarea__inner) {
  resize: none;
  border-radius: 8px;
}

:deep(.markdown-body) {
  background: transparent !important;
}

:deep(pre) {
  background-color: var(--el-color-primary-light-9) !important;
  padding: 12px;
  border-radius: 4px;
  margin: 8px 0;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
